package com.quanquan.management.config;

import com.quanquan.management.core.utils.DecriptUtils;
import com.quanquan.management.entity.*;
import com.quanquan.management.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author:lihonglinag
 * @date:2019-03-21 11:41
 * @version:v 1.0.0
 */
@Service
public class InitDataUtil {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysRoleRepository sysRoleRepository;

    @Autowired
    private SysRoleUserRepository sysRoleUserRepository;

    @Autowired
    private SysPermissionRepository sysPermissionRepository;

    @Autowired
    private SysPermissionRoleRepository sysPermissionRoleRepository;

    @PostConstruct
    public void dataInit() {
        String baseUsername = "admin";
        String basePassword = "123456";
        String basePhone = "18751976175";
        SysUser user = sysUserRepository.findByUsername(baseUsername);
        if (user == null) {
            user = new SysUser();
            user.setUsername(baseUsername);
            user.setPassword(DecriptUtils.md5(basePassword));
            user.setPhone(basePhone);
            user.setRegTime(new Date());
            user.setNickname("超级管理员");
            sysUserRepository.saveAndFlush(user);
        }
        List<SysRole> roleLst = sysRoleRepository.getRoleByUserId(user.getId());
        String roleId = "";
        if (roleLst.size() == 0) {
            SysRole role = new SysRole();
            role.setName("超级管理员");
            role.setRegTime(new Date());
            role.setUpdateTime(new Date());
            sysRoleRepository.saveAndFlush(role);

            SysRoleUser roleUser = new SysRoleUser();
            roleUser.setRoleId(role.getId());
            roleUser.setUserId(user.getId());
            sysRoleUserRepository.save(roleUser);
            roleId=role.getId();
        }else{
            for (SysRole sysRole : roleLst) {
                roleId=sysRole.getId();
                break;
            }
        }


        List<SysPermission> permissionList=sysPermissionRepository.getPermissionByUserId(user.getId());
        if(permissionList.size()==0){
            SysPermission permission=new SysPermission();
            permission.setDescription("主页-全量数据统计");
            permission.setName("主页");
            permission.setParentId("");
            permission.setRegTime(new Date());
            permission.setUrl("/index");
            permission.setUpdateTime(new Date());
            sysPermissionRepository.saveAndFlush(permission);
            SysPermissionRole permissionRole=new SysPermissionRole();
            permissionRole.setRoleId(roleId);
            permissionRole.setPermissionId(permission.getId());
            sysPermissionRoleRepository.saveAndFlush(permissionRole);
        }


    }
}
